package com.hag.equipment_server.netty.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
    private Header header;
    private ByteBuf body;
    private ByteBuf tail;
    private ByteBuf all;

    private enum COMMAND_ID {
        optical1(0x01),
        optical2(0x02),
        vibrate1(0x08),
        vibrate2(0x09);

        private int value;

        COMMAND_ID(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

    }

    public com.hag.equipment_server.netty.server.Data toData() {
        com.hag.equipment_server.netty.server.Data data = new com.hag.equipment_server.netty.server.Data();

        //type
        int command_id = header.getCOMMAND_ID();
        String type = null;
        if (command_id == COMMAND_ID.optical1.getValue()) {
            type = "optical1";
        } else if (command_id == COMMAND_ID.optical2.getValue()) {
            type = "optical2";
        } else if (command_id == COMMAND_ID.vibrate1.getValue()) {
            type = "vibrate1";
        } else if (command_id == COMMAND_ID.vibrate2.getValue()) {
            type = "vibrate2";
        }
        data.setType(type);


        List list = new ArrayList();
        if (type.indexOf("optical") == -1) {
            while (body.isReadable()) {
                long item = body.readUnsignedIntLE();
                list.add(item);
            }
        } else {
            while (body.isReadable()) {
                int item = body.readUnsignedShortLE();
                list.add(item);
                if (tail.isReadable()) {
                    int difference = tail.readUnsignedShortLE();
                    data.setDifference(difference+"");
                }
                if (tail.isReadable()) {
                    int breaking = tail.readUnsignedShortLE();
                    data.setBreaking(breaking+"");
                }

            }
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            String s = mapper.writeValueAsString(list);
            data.setData(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return data;
    }
}
